﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Sinc.ERP.Core.Enum;

namespace Sinc.ERP.Application;

/// <summary>
/// 供应商服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class SupplierService : CustomBaseService, IDynamicApiController
{
    private readonly SqlSugarRepository<Supplier> _supplierRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SupplierService(SqlSugarRepository<Supplier> supplierRep, ISqlSugarClient sqlSugarClient)
    {
        _supplierRep = supplierRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 查询所有供应商 🔍
    /// </summary>
    /// <returns></returns>
    [DisplayName("查询所有供应商")]
    [ApiDescriptionSettings(Name = "dropdownData"), HttpPost]
    public async Task<IList<SupplierOutput>> DropdownData()
    {
        return await _supplierRep.AsQueryable().Select<SupplierOutput>().ToListAsync();
    }

    /// <summary>
    /// 分页查询供应商 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询供应商")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SupplierOutput>> Page(PageSupplierInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _supplierRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Name.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status.Value)
            .WhereIF(input.Type.HasValue, u => u.Type == input.Type.Value)
            .Select<SupplierOutput>();
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取供应商详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取供应商详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Supplier> Detail([FromQuery] QueryByIdSupplierInput input)
    {
        return await _supplierRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加供应商 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加供应商")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSupplierInput input)
    {
        var entity = input.Adapt<Supplier>();
        if (await _supplierRep.IsAnyAsync(u => u.Name != null && u.Name == input.Name)) throw Oops.Oh("供应商名称已存在");
        return await _supplierRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新供应商 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新供应商")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSupplierInput input)
    {
        if (await _supplierRep.IsAnyAsync(u => u.Id != input.Id && u.Name != null && u.Name == input.Name)) throw Oops.Oh("供应商名称已存在");
        var entity = input.Adapt<Supplier>();
        await _supplierRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除供应商 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除供应商")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSupplierInput input)
    {
        var entity = await _supplierRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _supplierRep.FakeDeleteAsync(entity);   //假删除
        //await _supplierRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除供应商 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除供应商")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")] List<DeleteSupplierInput> input)
    {
        var exp = Expressionable.Create<Supplier>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _supplierRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();

        return await _supplierRep.FakeDeleteAsync(list);   //假删除
        //return await _supplierRep.DeleteAsync(list);   //真删除
    }

    /// <summary>
    /// 导出供应商记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出供应商记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSupplierInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSupplierOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "供应商导出记录");
    }

    /// <summary>
    /// 下载供应商数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载供应商数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSupplierOutput>(), "供应商导入模板");
    }

    /// <summary>
    /// 导入供应商记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入供应商记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportSupplierInput, Supplier>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x =>
                    {
                        if (x.Name.IsEmpty())
                        {
                            x.Error = "供应商名称不能为空";
                            return false;
                        }
                        if (!Enum.IsDefined(typeof(StatusEnum), x.Status))
                        {
                            x.Error = "供应商状态无效";
                            return false;
                        }
                        if (!Enum.IsDefined(typeof(SupplierTypeEnum), x.Type))
                        {
                            x.Error = "供应商类型无效";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Supplier>>();

                    var storageable = _supplierRep.Context.Storageable(rows)
                                    .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Name), "供应商名称不能为空")
                                    .SplitError(it => it.Item.Name?.Length > 100, "供应商名称长度不能超过100个字符")
                                    .WhereColumns(it => new { it.Name }).SplitError(it => it.Any(), "供应商名称已存在")
                                    .SplitInsert(_ => true)
                                    .ToStorage();

                    if (rows.Any())
                    {
                        storageable.BulkCopy();
                        storageable.BulkUpdate();
                    }
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });

            return stream;
        }
    }
}
